/*
 *   Copyright 2008 Mark Ashworth <javameme@gmail.com>.
 * 
 *   Licensed under the GNU General Public License v3 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 * 
 *        http://www.gnu.org/licenses/gpl-3.0.html
 * 
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *   under the License.
 */
package xperiment.metaphor.model.entity;

import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.apache.commons.lang.builder.CompareToBuilder;
import xperiment.metaphor.model.ModelException;
import xperiment.metaphor.model.Persistent;
import xperiment.metaphor.model.XML;

/**
 * Contact relationship between two entities
 * @author Mark P Ashworth <javameme@gmail.com>
 * @version 1.0.0
 * @since 1.0.0
 */
@javax.persistence.Entity
@Inheritance(strategy=InheritanceType.JOINED)
@Table(name="contact")
public class Contact extends Relationship implements Persistent, XML {

    /** The type of contact (Personal, Business, Other) */
    @ManyToOne()
    private ContactType type;

    /**
     * Default constructor
     */
    public Contact() {
        super();
    }

    /**
     * Constructs the relation to the subject entity
     * @param subject The subject of the relationship
     * @param contactType The type of contact
     */
    public Contact(Entity subject, ContactType contactType) {
        super(subject);
        this.type = contactType;
    }

    public ContactType getType() {
        return type;
    }

    public void setType(ContactType type) {
        this.type = type;
    }

    /**
     * Saves the contact to the persistent store
     * @throws xperiment.metaphor.model.ModelException If there was an error
     */
    @Override
    public Contact save() throws ModelException {

        /*
         * Persist the contact type
         */
        if (getType() != null) {
            getType().attach(getApplicationManager());
            getType().save();
        }

        return (Contact) super.save();
    }

    /**
     * Compares relationships based upon the relationship and the
     * type of contact.
     *
     * @param o The object to compare to
     * @return int
     */
    @Override
    public int compareTo(Object o) {
        Contact rhs = (Contact) o;
        return new CompareToBuilder()
                .appendSuper(super.compareTo(o))
                .append(getType(), rhs.getType())
                .toComparison();
    }

    @Override
    public String toXML() {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
